package jp.spidernet.myphone;

import java.io.File;
import java.util.ArrayList;
import java.util.Stack;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyPhoneActivity extends Activity {
	private static final String TAG = "MyPhoneActivity";
	private ListView mListView = null;
	private File SDDIR = Environment.getExternalStorageDirectory();
	private File mCurrentDir = SDDIR;
	private ArrayList<File> mListFiles;
	private ArrayList<File> mCheckedFilesList = null;
	private TextView mTvCurrentDir = null;
	private Stack<Integer> mSelectedPosStack = new Stack<Integer>();
	private FileListAdapter mFilesListAdapter = null;
	private ArrayList<File> mCutFilesList = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mTvCurrentDir = (TextView) findViewById(R.id.tvCurrentDir);
		mTvCurrentDir.setText(mCurrentDir.getName());
		mListView = (ListView) findViewById(R.id.listView);
		registerForContextMenu(mListView);
		updateNewDir(mCurrentDir);
		mListView.setAdapter(mFilesListAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View view, int pos,
					long id) {
				File selectFile = mListFiles.get(pos);
				if (!selectFile.canRead()) {
					Toast.makeText(getBaseContext(), "Can't open",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (selectFile.isFile()) {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					String fileName = selectFile.getName();
					String extension = Utility.getFileExtension(fileName);
					String mimeType = null;
					if (Utility.APK.toLowerCase().equals(extension)) {
						mimeType = Utility.MIME_TYPE_APK;
					} else {
						mimeType = MimeTypeMap.getSingleton()
								.getMimeTypeFromExtension(extension);
						if (mimeType == null)
							mimeType = Utility.TEXT_PLAIN;
					}
					intent.setDataAndType(Uri.fromFile(selectFile), mimeType);
					try {
						startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					mSelectedPosStack.push(pos);
					updateNewDir(selectFile);
				}
			}
		});
	}

	@Override
	public void onBackPressed() {
		String name = mCurrentDir.getName();
		if ("".equals(name))
			super.onBackPressed();
		else
			upToParentDir(null);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = new MenuInflater(this);
		menuInflater.inflate(R.menu.options, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (mCutFilesList != null) {
			menu.findItem(R.id.itemMove).setTitle(R.string.paste);
		} else {
			menu.findItem(R.id.itemMove).setTitle(R.string.cut);
		}
		return super.onPrepareOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.itemDelete) {
			if (mCheckedFilesList != null) {
				for (File file : mCheckedFilesList) {
					file.delete();
					mListFiles.remove(file);
					mFilesListAdapter.notifyDataSetChanged();
				}
			}
		} else if (id == R.id.itemMove) {
			if (mCutFilesList != null) {
				Utility.move(mCutFilesList, mCurrentDir);
				updateNewDir(mCurrentDir);	
				mCutFilesList = null;
			} else {
				mCutFilesList = mCheckedFilesList;
			}
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		Log.v(TAG, "onCreateContextMenu was called");
		int id = v.getId();
		if (id == R.id.listView) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			menu.setHeaderTitle(mListFiles.get(info.position).getName());
//			String[] menuItems = getResources().getStringArray(
//					R.array.context_menu);
//			for (int i = 0; i < menuItems.length; i++) {
//				menu.add(info.position, i, i, menuItems[i]);
//			}
			menu.add(info.position, 0, 0, R.string.rename);
			if (mCutFilesList == null)
				menu.add(info.position, 1, 1, R.string.cut);
			else
				menu.add(info.position, 1, 1, R.string.paste);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();
		if (menuItemIndex == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			final EditText editText = new EditText(MyPhoneActivity.this);
			editText.setText(mListFiles.get(info.position).getName());
			builder.setMessage("Are you sure you want to change file?")
					.setView(editText)
					.setCancelable(false)
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									String newName = mCurrentDir.getPath()
											+ "/"
											+ editText.getText().toString();
									boolean result = Utility.rename(
											mListFiles.get(info.position),
											newName);
									if (result) {
										mListFiles.remove(info.position);
										mListFiles.add(info.position, new File(
												newName));
										mFilesListAdapter
												.notifyDataSetChanged();
									} else {
										Toast.makeText(getBaseContext(), "can't rename", Toast.LENGTH_SHORT).show();
									}
								}
							})
					.setNegativeButton(android.R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		} else if (menuItemIndex == 1) {
			if (mCutFilesList == null) { //cut
				mCutFilesList = new ArrayList<File>();
				mCutFilesList.add(mListFiles.get(info.position));
			} else { //paste
				Utility.move(mCutFilesList, mListFiles.get(info.position));
				mCutFilesList = null;
			}
		}
		return true;
	}

	public void upToParentDir(View v) {
		File upDir = mCurrentDir.getParentFile();
		if (upDir != null) {
			updateNewDir(upDir);
			if (!mSelectedPosStack.isEmpty())
				mListView.setSelection(mSelectedPosStack.pop());
		}
	}

	private void updateNewDir(File newFileDir) {
		mCurrentDir = newFileDir;
		mListFiles = Utility.makeFilesArrayList(mCurrentDir.listFiles());
		Utility.sortFilesList(mListFiles);
		mFilesListAdapter = new FileListAdapter(MyPhoneActivity.this,
				R.layout.listitem, mListFiles);
		mListView.setAdapter(mFilesListAdapter);
		mTvCurrentDir.setText(mCurrentDir.getName());
	}

	public ArrayList<File> getCheckedFilesList() {
		return mCheckedFilesList;
	}

	public void setCheckedFilesList(ArrayList<File> checkedFilesList) {
		this.mCheckedFilesList = checkedFilesList;
	}

}